package com.bite.dailyHomework.date1109;

import java.util.Random;

public class Demo_01 {
    public static void main(String[] args) throws InterruptedException{
        /**
         * 给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
         * 实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
         * 其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
         * 最终再汇总两个和, 进行相加
         * 记录程序的执行时间.
         */
        long begin = System.currentTimeMillis();
        int[] arr = new int[1000_0000];
        Random rand = new Random();
        for(int i = 0; i < arr.length; i++){
            arr[i] = rand.nextInt(100) + 1;
        }
        MyRunnable runnable1 = new MyRunnable(0, arr);
        MyRunnable runnable2 = new MyRunnable(1, arr);
        Thread t1 = new Thread(runnable1);
        Thread t2 = new Thread(runnable2);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(runnable1.sum + runnable2.sum);
        long end = System.currentTimeMillis();
        System.out.println("程序的执行时间是：" + (end - begin));
    }
}
class MyRunnable implements Runnable {
    private int num;
    private int[] arr;
    public int sum;
    public MyRunnable(int num, int[] arr) {
        this.num = num;
        this.arr = arr;
    }

    @Override
    public void run() {
        for(int i = 0; i < arr.length; i++){
            if(i % 2 == num){
                sum+= arr[i];
            }
        }
    }
}